package com.xiaohe.gulimall.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaohe.common.utils.PageUtils;
import com.xiaohe.common.utils.Query;

import com.xiaohe.gulimall.product.dao.CategoryDao;
import com.xiaohe.gulimall.product.entity.CategoryEntity;
import com.xiaohe.gulimall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }


    @Override
    public List<CategoryEntity> listWithTree() {
        //查询所有分类
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        //组装父子结构
        //找一级分类
        List<CategoryEntity> level1Menus = categoryEntities.stream().filter(
                categoryEntity -> categoryEntity.getParentCid() == 0)
                .map((menu)->{
                    menu.setChildren(getChildren(menu,categoryEntities));
                    return menu;
                }).sorted((menu1,menu2)->{
                    return (menu1.getSort()==null?0:menu1.getSort()) -(menu2.getSort()==null?0:menu2.getSort());
                })
                .collect(Collectors.toList());

        //找到一级分类的子分类
        return level1Menus;
    }

    @Override
    public void removeMenusByIds(List<Long> asList) {
        //TODO 1、检查当前删除的菜单是否被其他地方引用
        baseMapper.deleteBatchIds(asList);
    }


    /**
     * 递归函数查找子菜单
     * @param root
     * @param all
     * @return
     */
    private List<CategoryEntity> getChildren(CategoryEntity root,List<CategoryEntity> all){
        List<CategoryEntity> children = all.stream().filter((categoryEntity) -> {
            return categoryEntity.getParentCid() == root.getCatId();
        }).map((item)->{
            item.setChildren(getChildren(item,all));
            return item;
        }).sorted((menu1,menu2)->(menu1.getSort()==null?0:menu1.getSort()) -(menu2.getSort()==null?0:menu2.getSort())).collect(Collectors.toList());
        return  children;
    }

}